package com.aaa.controller;

import com.aaa.entity.DataBackup;
import com.aaa.entity.R;
import com.aaa.entity.User;
import com.aaa.mapper.DataBackupMapper;
import com.aaa.utils.MysqlBackup;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据备份相关接口
 */
@RestController
@RequestMapping("/dataBackup")
public class DataBackupController {

    @Resource
    private DataBackupMapper dataBackupMapper;

    @Autowired
    private MysqlBackup mysqlBackup;

    /**
     * 分页查询备份信息
     */
    @RequestMapping("/selectPage")
    public Object selectPage(DataBackup dataBackup,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer limit) {
        PageHelper.startPage(page, limit);
        List<DataBackup> list = dataBackupMapper.selectList(dataBackup);
        PageInfo<DataBackup> pageInfo = new PageInfo<>(list);
        Map<String, Object> data = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        data.put("code", 0);
        data.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        data.put("count", pageInfo.getTotal());
        //将分页后的数据返回（每页要显示的数据）
        data.put("data", pageInfo.getList());
        return data;
    }

    /**
     * 备份数据
     */
    @RequestMapping("/backup")
    public R backup(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");

        boolean b = mysqlBackup.dbBackup(user.getLoginname());
        return b ? R.ok() : R.error();
    }


    /**
     * 下载备份文件
     */
    @RequestMapping("/download/{id}")
    public void downloadFile(@PathVariable("id") Integer id, HttpServletResponse response) {
        OutputStream os = null;
        InputStream is = null;
        DataBackup dataBackup = dataBackupMapper.selecOne(id);
        try {
            String[] split = dataBackup.getFileUrl().split("\\\\");
            String fileName = split[split.length - 1];
            // 取得输出流
            os = response.getOutputStream();
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=utf-8");
            //Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，
            // 保存类型以Content中设置的为准。注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。
            //把文件名按UTF-8取出，并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码，中文不要太多，最多支持17个中文，因为header有150个字节限制。
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //读取流
            File f = new File(dataBackup.getFileUrl());

            is = new FileInputStream(f);

            //复制
            IOUtils.copy(is, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
